package com.atguigu.juc.safe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class NotSafeDemo {
    public static void main(String[] args) {

    }
    private static void listNotSafe() {
//        List<String> list = new ArrayList<>();

        //解决方案一：使用线程安全的Vector   --->   Vector底层代码的add方法是加synchronized锁了的
        //List<String> list = new Vector<>();

        //解决方案二：使用Collections工具类中的将ArrayList数组包装成线程安全的
        //List<String> list = Collections.synchronizedList(new ArrayList<>());

        //解决方案三: 使用CopyOnWriteArrayList--->读写分离，写时复制
        //使用CopyOnWriteArraySet
        //使用ConcurrentHasMap原理：分段锁
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 1; i <= 50; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(list);
            }, "A").start();
        }
    }

    private static void setNotSafe() {
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 1; i <= 50; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(set);
            }, "A").start();
        }
    }

    private static void mapNotSafe() {
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 1; i <= 50; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 6));
                System.out.println(map);
            }, "A").start();
        }

    }
    }

